package com.example.woke;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.http.HttpMethods;
import com.netease.nim.uikit.GlideApp;
import com.woke.addressactivity.BaseActivity;
import com.woke.httpupload.FileProviderUtils;
import com.woke.method.MyApp;
import com.zhongcai.online.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.List;

import cn.xl.xxl.imagecache.ImageLoader;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class MyShoukuanActivity extends BaseActivity implements OnClickListener, EasyPermissions.PermissionCallbacks {

	private MyApp myapp;
	private ImageLoader imageLoader;
	private int screenHigth, screenWidth;
	private ImageView mErweima, saveBtn;
	private LinearLayout savedView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate (savedInstanceState);
		setContentView (R.layout.activity_myshoukuan);
		findViewById (R.id.avabout_image_back).setOnClickListener (this);

		myapp = (MyApp) getApplication ();
		imageLoader = new ImageLoader (this);
		screenHigth = myapp.screenHigth;
		screenWidth = myapp.screenWidth;

		savedView = (LinearLayout) findViewById (R.id.erweimaView);
		saveBtn = (ImageView) findViewById (R.id.saveImgBtn);
		mErweima = (ImageView) findViewById (R.id.imgErweima);
		LayoutParams params = mErweima.getLayoutParams ();
		params.width = screenWidth / 5 * 4;
		params.height = screenWidth / 5 * 4;
		mErweima.setLayoutParams (params);

		getMyShoukuanma ();
		saveBtn.setOnClickListener (this);
	}

	private void getMyShoukuanma() {
		if (myapp.getDatas_load () == null) return;
		HttpMethods.getInstance ()
				.businessSeriesNo (mQrCodeUrlObserver, Integer.parseInt (myapp.getDatas_load ()
						.getId ()));
//		HttpMethods.getInstance ()
//				.oldBusinessSeriesNo (mQrCodeUrlObserver, Integer.parseInt (myapp.getDatas_load ()
//						.getId ()));

	}

	private Observer<String> mQrCodeUrlObserver = new Observer<String> () {
		@Override
		public void onSubscribe(Disposable d) {

		}

		@Override
		public void onNext(String value) {
			if (TextUtils.isEmpty (value)) {
				Toast.makeText (MyShoukuanActivity.this, "您还未绑定商家收款码", Toast.LENGTH_SHORT).show ();
			} else {
				String qrCordUrl = value;
				if (! value.startsWith ("http")) {
					qrCordUrl = "http://" + value;
				}
				GlideApp.with (MyShoukuanActivity.this)
						.load (qrCordUrl)
						.placeholder(R.mipmap.icn__launch_oem)
						.error(R.mipmap.icn__launch_oem)
						.into (mErweima);
			}
		}

		@Override
		public void onError(Throwable e) {
			Toast.makeText (MyShoukuanActivity.this, e.getMessage (), Toast.LENGTH_SHORT).show ();
		}

		@Override
		public void onComplete() {

		}
	};

	public void viewSaveToImage(View view) {
		boolean isOk = false;
		view.setDrawingCacheEnabled (true);
		view.setDrawingCacheQuality (View.DRAWING_CACHE_QUALITY_HIGH);
		view.setDrawingCacheBackgroundColor (Color.WHITE);

		// 把一个View转换成图片
		Bitmap cachebmp = loadBitmapFromView (view);

		FileOutputStream fos = null;
		final File file = FileProviderUtils.createImageFile (this);
		if (file != null) {
			try {
				fos = new FileOutputStream (file);
				cachebmp.compress (Bitmap.CompressFormat.PNG, 90, fos);

				fos.flush ();
				fos.close ();
				runOnUiThread (new Runnable () {
					@Override
					public void run() {
						Toast.makeText (MyShoukuanActivity.this, "二维码保存成功" + file.getPath (), Toast.LENGTH_LONG)
								.show ();
					}
				});

				try {
					String path = MediaStore.Images.Media.insertImage (getContentResolver (), file.getAbsolutePath (), "1_shoukuanma.png", "我的收款码");
					Intent intent2 = new Intent (Intent.ACTION_MEDIA_MOUNTED, Uri.fromFile (new File (path)));
					intent2.addFlags (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
					sendBroadcast (intent2);

					Intent intent = new Intent (Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile (new File (path)));
					intent.addFlags (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
					sendBroadcast (intent);
				} catch (FileNotFoundException e) {
					e.printStackTrace ();
				}

			} catch (Exception e) {
				e.printStackTrace ();
			}


		}
		view.setDrawingCacheEnabled (false);

	}

	private Bitmap loadBitmapFromView(View v) {
		int w = v.getWidth ();
		int h = v.getHeight ();

		Bitmap bmp = Bitmap.createBitmap (w, h, Bitmap.Config.ARGB_8888);
		Canvas c = new Canvas (bmp);

		c.drawColor (Color.WHITE);
		/** 如果不设置canvas画布为白色，则生成透明 */

		v.draw (c);

		return bmp;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId ()) {
			case R.id.avabout_image_back:
				finish ();
				break;
			case R.id.saveImgBtn:
				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
					methodRequiresTwoPermission ();
				} else {
					viewSaveToImage (savedView);
				}
				break;

			default:
				break;
		}
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		super.onRequestPermissionsResult (requestCode, permissions, grantResults);
		EasyPermissions.onRequestPermissionsResult (requestCode, permissions, grantResults, this);
	}

	private static final int READ_AND_WRITE_STORE = 88;

	@AfterPermissionGranted(READ_AND_WRITE_STORE)
	private void methodRequiresTwoPermission() {
		String[] perms = {Manifest.permission.READ_EXTERNAL_STORAGE};
		if (EasyPermissions.hasPermissions (this, perms)) {
			// Already have permission, do the thing
			Log.e ("MainActivity", "已经获得读写本地文件的权限");
			viewSaveToImage (savedView);
		} else {
			// Do not have permissions, request them now
			EasyPermissions.requestPermissions (this, "需要读写手机存储权限",
					READ_AND_WRITE_STORE, perms);
		}
	}

	@Override
	public void onPermissionsGranted(int requestCode, List<String> perms) {
		if (requestCode == READ_AND_WRITE_STORE) {
			viewSaveToImage (savedView);
		}
	}

	@Override
	public void onPermissionsDenied(int requestCode, List<String> perms) {
		if (requestCode == READ_AND_WRITE_STORE) {
			new AlertDialog.Builder (this).setMessage ("请在<权限管理>里打开读写手机存储权限")
					.setPositiveButton ("前往", new DialogInterface.OnClickListener () {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							Intent intent = new Intent (Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
							intent.setData (Uri.fromParts ("package", getPackageName (), null));
							startActivity (intent);
							dialog.dismiss ();
						}
					})
					.setNegativeButton ("取消", null)
					.create ()
					.show ();
		}
	}


}
